from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPixmap, QFont
from qfluentwidgets import (SmoothScrollArea, PrimaryPushButton, InfoBar,
                            InfoBarPosition, IconWidget, FluentIcon)
from modules import QuadrantModule
import os


class HoverMoveButton(PrimaryPushButton):
    def __init__(self, icon=None, text='', parent=None):
        if icon and text:
            super().__init__(icon, text, parent)
        elif icon:
            super().__init__(icon, parent)
        elif text:
            super().__init__(text, parent)
        else:
            super().__init__(parent)
        self.original_pos = self.pos()
        self.move_offset = QPoint(5, 5)  # 向右下角移动的偏移量

    def enterEvent(self, event):
        self.original_pos = self.pos()
        self.move(self.pos() + self.move_offset)
        super().enterEvent(event)

    def leaveEvent(self, event):
        self.move(self.original_pos)
        super().leaveEvent(event)


class QuadrantInterface(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.vBoxLayout = QVBoxLayout(self.view)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        # 初始化图片显示组件
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setMinimumSize(600, 400)
        self.image_label.setStyleSheet('''
            QLabel {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 8px;
                border: 1px solid rgba(255, 255, 255, 0.2);
            }
        ''')

        # 设置背景图片
        self.setStyleSheet('''
            QWidget {
                background-image: url(pic/background2.png);
                border: none;
            }
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
        ''')

        # 将背景样式直接应用到主视图
        self.view.setStyleSheet('''
            QWidget#mainView {
                border-image: url(pic/background2.png) 0 0 0 0 stretch stretch;
            }
        ''')
        self.view.setObjectName("mainView")

        # 添加中间层图片
        self.bg_image = QLabel(self.view)
        self.bg_image.setPixmap(QPixmap("pic/xiangxianchuli.png"))
        self.bg_image.setScaledContents(True)
        self.bg_image.setStyleSheet('background: transparent;')
        self.bg_image.lower()

        # 添加设置确保左侧面板背景透明
        self.setStyleSheet('''
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
            QPushButton {
                border: none;
                background-color: transparent;
            }
            QWidget {
                background: transparent;
            }
        ''')

        self.initUI()

    def initUI(self):
        # 创建水平布局作为主布局
        main_layout = QHBoxLayout()
        main_layout.setSpacing(40)

        # 创建左侧控制面板布局
        left_panel = QVBoxLayout()
        left_panel.setAlignment(Qt.AlignCenter)
        left_panel.setSpacing(40)

        # 增加顶部空白
        left_panel.addSpacing(200)

        # 添加状态标签
        self.status_label = QLabel("等待处理...")
        self.status_label.setFont(QFont("Microsoft YaHei", 14))
        self.status_label.setStyleSheet('color: white;')
        self.status_label.setAlignment(Qt.AlignCenter)
        left_panel.addWidget(self.status_label)

        # 处理按钮
        self.process_button = HoverMoveButton(parent=self.view)
        process_pixmap = QPixmap("pic/kaishichuli.png")
        self.process_button.setFixedSize(process_pixmap.size())
        self.process_button.setStyleSheet('''
            PrimaryPushButton {
                border: none;
                background-image: url(pic/kaishichuli.png);
                background-position: center;
                background-repeat: no-repeat;
                background-color: transparent;
            }
            PrimaryPushButton:hover {
                background-color: transparent;
            }
            PrimaryPushButton:pressed {
                background-color: transparent;
            }
        ''')
        self.process_button.clicked.connect(self.process_quadrants)
        left_panel.addWidget(self.process_button)

        # 查看结果按钮
        self.view_button = HoverMoveButton(parent=self.view)
        view_pixmap = QPixmap("pic/chakanjieguo.png")
        self.view_button.setFixedSize(view_pixmap.size())
        self.view_button.setStyleSheet('''
            PrimaryPushButton {
                border: none;
                background-image: url(pic/chakanjieguo.png);
                background-position: center;
                background-repeat: no-repeat;
                background-color: transparent;
            }
            PrimaryPushButton:hover {
                background-color: transparent;
            }
            PrimaryPushButton:pressed {
                background-color: transparent;
            }
        ''')
        self.view_button.clicked.connect(self.view_results)
        self.view_button.setEnabled(False)
        left_panel.addWidget(self.view_button)

        # 添加底部弹性空间
        left_panel.addStretch()

        # 创建左侧面板容器，修改宽度
        left_widget = QWidget()
        left_widget.setLayout(left_panel)
        left_widget.setFixedWidth(400)  # 从300增加到400
        left_widget.setStyleSheet('''
            QWidget {
                background: transparent;
            }
        ''')

        # 将左侧面板添加到主布局
        main_layout.addWidget(left_widget)

        # 创建右侧的垂直布局来放置显示区域和控制按钮
        right_panel = QVBoxLayout()
        right_panel.setAlignment(Qt.AlignTop)  # 设置靠上对齐

        # 添加一些顶部空间
        right_panel.addSpacing(150)  # 减少顶部间距

        # 创建右侧显示区域，调整样式以完全铺满图片
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setFixedSize(550, 550)
        self.image_label.setStyleSheet('''
            QLabel {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                padding: 0px;  /* 移除内边距 */
            }
        ''')
        right_panel.addWidget(self.image_label)

        # 添加缩放控制按钮到显示区域下方
        control_layout = QHBoxLayout()
        control_layout.setContentsMargins(0, 10, 0, 10)
        control_layout.setSpacing(10)  # 减小按钮间距

        # 缩放按钮
        self.zoom_in_btn = HoverMoveButton(FluentIcon.ZOOM_IN, "放大", self.view)
        self.zoom_in_btn.setFixedSize(150, 45)
        self.zoom_in_btn.clicked.connect(lambda: self.adjust_image_scale(1.2))

        self.zoom_out_btn = HoverMoveButton(FluentIcon.ZOOM_OUT, "缩小", self.view)
        self.zoom_out_btn.setFixedSize(150, 45)
        self.zoom_out_btn.clicked.connect(lambda: self.adjust_image_scale(0.8))

        self.reset_btn = HoverMoveButton(FluentIcon.SYNC, "重置", self.view)
        self.reset_btn.setFixedSize(150, 45)
        self.reset_btn.clicked.connect(self.reset_image_size)

        # 隐藏初始控制按钮
        self.zoom_in_btn.hide()
        self.zoom_out_btn.hide()
        self.reset_btn.hide()

        control_layout.addWidget(self.zoom_in_btn)
        control_layout.addWidget(self.zoom_out_btn)
        control_layout.addWidget(self.reset_btn)

        # 将控制按钮布局添加到右侧面板
        right_panel.addLayout(control_layout)

        # 将右侧面板添加到主布局
        main_layout.addLayout(right_panel)

        # 设置主布局
        self.vBoxLayout.addLayout(main_layout)

    def process_quadrants(self):
        try:
            self.clear_image()
            self.status_label.setText('正在处理数据...')
            self.process_button.setEnabled(False)
            self.view_button.setEnabled(False)

            QuadrantModule.process_and_save_quadrants()

            self.status_label.setText('处理完成!')
            self.view_button.setEnabled(True)

            InfoBar.success(
                title='成功',
                content='象限数据处理完成',
                position=InfoBarPosition.TOP,
                parent=self
            )
        except Exception as e:
            self.status_label.setText('处理失败!')
            InfoBar.error(
                title='错误',
                content=f'数据处理出错: {str(e)}',
                position=InfoBarPosition.TOP,
                parent=self
            )
        finally:
            self.process_button.setEnabled(True)

    def view_results(self):
        """在界面内显示可视化结果"""
        try:
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            image_path = os.path.join(current_dir, "data", "quadrant_visualization.png")

            if os.path.exists(image_path):
                self.image_label.setUpdatesEnabled(False)
                pixmap = QPixmap(image_path)

                if not pixmap.isNull():
                    # 显示控制按钮
                    self.zoom_in_btn.show()
                    self.zoom_out_btn.show()
                    self.reset_btn.show()

                    # 初始缩放显示
                    self.reset_image_size()
                else:
                    raise Exception("图片文件已损坏")
            else:
                raise Exception("可视化图片不存在，请先进行象限处理")
        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'显示结果出错: {str(e)}',
                position=InfoBarPosition.TOP,
                parent=self
            )
        finally:
            self.image_label.setUpdatesEnabled(True)

    def adjust_image_scale(self, factor):
        """调整图片缩放比例"""
        current_pixmap = self.image_label.pixmap()
        if current_pixmap:
            new_width = int(current_pixmap.width() * factor)
            new_height = int(current_pixmap.height() * factor)

            # 限制最小尺寸
            if new_width < 100 or new_height < 100:
                return

            scaled_pixmap = current_pixmap.scaled(
                new_width,
                new_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )
            self.image_label.setPixmap(scaled_pixmap)

    def reset_image_size(self):
        """重置图片到适合窗口的尺寸"""
        current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        image_path = os.path.join(current_dir, "data", "quadrant_visualization.png")
        if os.path.exists(image_path):
            pixmap = QPixmap(image_path)
            scaled_pixmap = pixmap.scaled(
                self.image_label.width(),  # 移除减去的20像素
                self.image_label.height(),  # 移除减去的20像素
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )
            self.image_label.setPixmap(scaled_pixmap)

    def clear_image(self):
        """清除当前显示的图片"""
        if self.image_label.pixmap():
            self.image_label.pixmap().detach()
        self.image_label.clear()
        self.zoom_in_btn.hide()
        self.zoom_out_btn.hide()
        self.reset_btn.hide()

    def resizeEvent(self, event):
        """重写调整大小事件以确保图片始终填满界面"""
        super().resizeEvent(event)
        self.bg_image.setGeometry(0, 0, self.view.width(), self.view.height())
        if self.image_label.pixmap():
            self.reset_image_size()

